package com.wholeintech.zigbee.gw;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import com.wholeintech.utils.CommonUtil;
import com.wholeintech.zigbee.util.SerialDataUnpack;

/**
 * Created by Lyle on 2016-01-18.
 */
public class ZigBeeDataProcess {

    private static final String TAG = "ZigBeeDataProcess";
    public static final int UNPACK_RX_DATA = 2001;
    public static final int RESTART_SERVICE = 2018;

    private static final boolean rxDebug = true;
    private SerialDataUnpack mSerialDataUnpack;
    private static boolean state = false;
    Handler mRxHandler;
    Context mContext;

    public ZigBeeDataProcess(Handler handler, Context context) {
        mRxHandler = handler;
        mContext = context;
    }

    public boolean startDataProcess() {
        if (!state) {
            mSerialDataUnpack = SerialDataUnpack.getSingleInstance(mContext);
            if (mSerialDataUnpack.initSerial()) {
                mSerialDataUnpack.startRx(mRxHandler);

                state = true;
                Log.d(TAG, "startDataProcess");
            } else {
                return false;
            }
        }
        return true;
    }

    public void stopDataProcess() {
        if (mSerialDataUnpack != null) {
            mSerialDataUnpack.stopRx();
            mSerialDataUnpack.ReleaseObj();
            state = false;
        }
    }

    /**
     *
     * @param cmd
     * @param code
     */
    public void TxPackDataBuffer(byte cmd, byte[] code) {
        byte[] Txdata = new byte[code.length + 5];
        Txdata[0] = (byte) 0xfc;
        Txdata[1] = (byte) code.length;
        Txdata[2] = (byte) 0x00;
        Txdata[3] = (byte) cmd;
        System.arraycopy(code, 0, Txdata, 4, code.length);
        Txdata[Txdata.length - 1] = CommonUtil.getSeekXorChecksum(Txdata, 1,
                (Txdata.length - 1));
        if (mSerialDataUnpack != null)
            mSerialDataUnpack.writeCmd(Txdata);
    }
}
